import { GlobalStore } from "@/store";
import axios from "axios";
import { ElMessage } from "element-plus";

// token的消息头
const TOKEN_HEADER = "Authorization";

//console.log("-----env", process.env.NODE_ENV);

let BASE_URL = process.env.NODE_ENV;
if (process.env.NODE_ENV == "production") {
  BASE_URL = "https://cms-api.imobybox.com";
} else {
  BASE_URL = "http://test-cms-api.imobybox.com";
}

// 创建axios对象
const requestHttp = axios.create({
  baseURL: `${BASE_URL}/api`,
  timeout: 10000,
});

// ================================= 请求拦截器 =================================

requestHttp.interceptors.request.use(
  (config) => {
    // 在发送请求之前消息头加入token token
    const globalStore = GlobalStore();

    if (globalStore.token) {
      config.headers[TOKEN_HEADER] = `Token ${globalStore.token}`;
    } else {
      delete config.headers[TOKEN_HEADER];
    }
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// ================================= 响应拦截器 =================================

// 添加响应拦截器
requestHttp.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    const res = response.data;
    if (res.code && res.code !== 0) {
      ElMessage({
        showClose: true,
        message: res.message,
        type: "error",
      });
      return Promise.reject(response);
    } else {
      // ElMessage({
      //     showClose: true,
      //     message: res.message,
      //     type: 'success'
      // })
      return Promise.resolve(res);
    }
  },
  (error) => {
    // 对响应错误做点什么
    if (error.message.indexOf("timeout") != -1) {
      ElMessage({
        showClose: true,
        message: "网络超时",
        type: "error",
      });
    } else if (error.message == "Network Error") {
      ElMessage({
        showClose: true,
        message: "网络连接错误",
        type: "error",
      });
    } else if (error.message.indexOf("Request") != -1) {
      ElMessage({
        showClose: true,
        message: "网络发生错误",
        type: "error",
      });
    }
    return Promise.reject(error);
  }
);

// ================================= 对外提供请求方法：通用请求，get， post, 下载download等 =================================

/**
 * 通用请求封装
 * @param config
 */
export const request = (config) => {
  return requestHttp.request(config);
};

/**
 * post请求
 */
export const postRequest = (url, data, responseType) => {
  const type = responseType || "json";
  return request({ data, url, method: "post", responseType: type });
};

/**
 * get请求
 */
export const getRequest = (url, params, responseType) => {
  const type = responseType || "json";
  return request({ url, method: "get", params, responseType: type });
};

/**
 * delete请求
 */
export const deleteRequest = (url, params) => {
  return request({ url, method: "delete", params });
};
